<template>
  <div class="glass-login">
    <!-- Ambient background elements -->
    <div class="ambient-bg">
      <div class="ambient-circle ambient-circle-1"></div>
      <div class="ambient-circle ambient-circle-2"></div>
      <div class="ambient-circle ambient-circle-3"></div>
      <div class="ambient-circle ambient-circle-4"></div>
    </div>
    
    <!-- Main login container -->
    <div class="login-container">
      <!-- Welcome section -->
      <div class="welcome-section glass-card">
        <div class="welcome-content">
          <div class="logo-section">
            <div class="logo-icon">
              <svg-icon icon-class="system" class="logo-svg" />
            </div>
            <h1 class="system-title">{{ title }}</h1>
          </div>
          <p class="welcome-text">欢迎使用建筑安全管理系统</p>
          <div class="feature-list">
            <div class="feature-item">
              <svg-icon icon-class="monitor" class="feature-icon" />
              <span>实时监控</span>
            </div>
            <div class="feature-item">
              <svg-icon icon-class="star" class="feature-icon" />
              <span>智能分析</span>
            </div>
            <div class="feature-item">
              <svg-icon icon-class="time" class="feature-icon" />
              <span>高效管理</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Login form section -->
      <div class="form-section">
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="glass-login-form">
          <div class="form-header">
            <h2 class="form-title">登录账户</h2>
            <p class="form-subtitle">请输入您的登录凭据</p>
          </div>
          
          <div class="form-content">
            <el-form-item prop="username" class="glass-form-item">
              <div class="input-wrapper">
                <div class="input-icon">
                  <svg-icon icon-class="user" />
                </div>
                <el-input
                  v-model="loginForm.username"
                  type="text"
                  size="large"
                  auto-complete="off"
                  placeholder="请输入账号"
                  class="glass-input"
                />
              </div>
            </el-form-item>
            
            <el-form-item prop="password" class="glass-form-item">
              <div class="input-wrapper">
                <div class="input-icon">
                  <svg-icon icon-class="password" />
                </div>
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  size="large"
                  auto-complete="off"
                  placeholder="请输入密码"
                  class="glass-input"
                  @keyup.enter="handleLogin"
                />
              </div>
            </el-form-item>
            
            <el-form-item prop="code" v-if="captchaEnabled" class="glass-form-item captcha-item">
              <div class="captcha-wrapper">
                <div class="input-wrapper captcha-input">
                  <div class="input-icon">
                    <svg-icon icon-class="validCode" />
                  </div>
                  <el-input
                    v-model="loginForm.code"
                    size="large"
                    auto-complete="off"
                    placeholder="验证码"
                    class="glass-input"
                    @keyup.enter="handleLogin"
                    @input="handleCodeInput"
                  />
                </div>
                <div class="captcha-image glass-card glass-card--sm" @click="getCode">
                  <img :src="codeUrl" class="captcha-img" alt="验证码"/>
                  <div class="refresh-hint">点击刷新</div>
                </div>
              </div>
            </el-form-item>
            
            <div class="form-options">
              <el-checkbox v-model="loginForm.rememberMe" class="remember-checkbox">
                记住密码
              </el-checkbox>
              <router-link v-if="register" class="forgot-link" :to="'/register'">
                立即注册
              </router-link>
            </div>
            
            <el-form-item class="submit-item">
              <el-button
                :loading="loading"
                size="large"
                type="primary"
                class="glass-login-btn"
                @click.prevent="handleLogin"
              >
                <span v-if="!loading">
                  <svg-icon icon-class="user" class="btn-icon" />
                  登录系统
                </span>
                <span v-else class="loading-text">
                  <div class="loading-spinner"></div>
                  登录中...
                </span>
              </el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
    </div>
    
    <!-- Footer info -->
    <div class="footer-info">
      <p>&copy; 2024 建筑安全管理系统. 保留所有权利.</p>
    </div>
  </div>
</template>

<script setup>
import { getCodeImg } from "@/api/login"
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'

const title = '建筑安全管理系统'
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  code: "",
  uuid: ""
})

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
}

const codeUrl = ref("")
// const loading = ref(false) // 注释掉本地loading状态
// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)

// 使用全局的loginLoading状态
const loading = computed(() => userStore.loginLoading)

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect
    // 如果当前在登录页，重置loading状态
    if (newRoute.path === '/login') {
        userStore.setLoginLoading(false)
    }
}, { immediate: true })

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      userStore.setLoginLoading(true)
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 })
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        // 登录成功后直接跳转，让权限验证来处理角色检查和路由生成
        const query = route.query
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        router.push({ path: redirect.value || "/", query: otherQueryParams })
      }).catch(() => {
        userStore.setLoginLoading(false)
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}

function handleCodeInput(value) {
  // 只允许输入数字，过滤掉非数字字符
  loginForm.value.code = value.replace(/\D/g, '')
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.value.uuid = res.uuid
    }
  })
}

function getCookie() {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}

getCode()
getCookie()

// 确保页面加载时loading状态为false
onMounted(() => {
    userStore.setLoginLoading(false)
    
    // 监听验证码刷新事件
    window.addEventListener('refreshCaptcha', () => {
        getCode()
    })
})

// 组件卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('refreshCaptcha', () => {
        getCode()
    })
})
</script>

<style lang='scss' scoped>
// Glass Login Page Styles
.glass-login {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #8b9dc3 0%, #a8b5d1 50%, #c4b5a0 100%);
  position: relative;
  overflow: hidden;
  padding: 20px;
}

// Ambient Background
.ambient-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 0;
  
  .ambient-circle {
    position: absolute;
    border-radius: 50%;
    background: linear-gradient(135deg, rgba(196, 149, 108, 0.15), rgba(212, 165, 116, 0.08));
    backdrop-filter: blur(10px);
    animation: float 25s infinite ease-in-out;
    
    &.ambient-circle-1 {
      width: 400px;
      height: 400px;
      top: -200px;
      right: -200px;
      animation-delay: 0s;
    }
    
    &.ambient-circle-2 {
      width: 300px;
      height: 300px;
      bottom: -150px;
      left: -150px;
      animation-delay: -8s;
    }
    
    &.ambient-circle-3 {
      width: 200px;
      height: 200px;
      top: 20%;
      left: 10%;
      animation-delay: -16s;
    }
    
    &.ambient-circle-4 {
      width: 150px;
      height: 150px;
      bottom: 30%;
      right: 15%;
      animation-delay: -24s;
    }
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.6;
  }
  25% {
    transform: translateY(-20px) rotate(90deg);
    opacity: 0.8;
  }
  50% {
    transform: translateY(20px) rotate(180deg);
    opacity: 0.4;
  }
  75% {
    transform: translateY(-10px) rotate(270deg);
    opacity: 0.7;
  }
}

// Main Login Container
.login-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
  max-width: 1000px;
  width: 100%;
  position: relative;
  z-index: 1;
}

// Welcome Section
.welcome-section {
  padding: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .welcome-content {
    text-align: center;
    color: var(--text-primary);
    
    .logo-section {
      margin-bottom: 32px;
      
      .logo-icon {
        width: 80px;
        height: 80px;
        margin: 0 auto 16px;
        background: linear-gradient(135deg, var(--accent-blue), var(--accent-orange));
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        box-shadow: 0 8px 32px rgba(66, 165, 245, 0.3);
        
        .logo-svg {
          font-size: 40px;
          color: white;
        }
      }
      
      .system-title {
        font-size: 28px;
        font-weight: 700;
        margin: 0;
        background: linear-gradient(135deg, var(--accent-primary), var(--accent-orange));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }
    }
    
    .welcome-text {
      font-size: 16px;
      color: var(--text-secondary);
      margin-bottom: 32px;
      line-height: 1.6;
    }
    
    .feature-list {
      display: flex;
      flex-direction: column;
      gap: 16px;
      
      .feature-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 16px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 12px;
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        &:hover {
          background: rgba(255, 255, 255, 0.15);
          transform: translateX(4px);
        }
        
        .feature-icon {
          font-size: 20px;
          color: var(--accent-primary);
        }
        
        span {
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
  }
}

// Form Section
.form-section {
  display: flex;
  align-items: center;
  justify-content: center;
}

.glass-login-form {
  width: 100%;
  max-width: 400px;
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.18);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  
  .form-header {
    text-align: center;
    margin-bottom: 32px;
    
    .form-title {
      font-size: 24px;
      font-weight: 700;
      color: var(--text-white);
      margin: 0 0 8px 0;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    .form-subtitle {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.8);
      margin: 0;
    }
  }
  
  .form-content {
    .glass-form-item {
      margin-bottom: 24px;
      
      :deep(.el-form-item__error) {
        color: #ff6b6b;
        font-size: 12px;
        background: rgba(255, 107, 107, 0.1);
        padding: 4px 8px;
        border-radius: 6px;
        backdrop-filter: blur(10px);
      }
    }
    
    .input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 12px;
      backdrop-filter: blur(10px);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      
      &:hover {
        background: rgba(255, 255, 255, 0.15);
        border-color: rgba(255, 255, 255, 0.3);
      }
      
      &:focus-within {
        background: rgba(255, 255, 255, 0.2);
        border-color: var(--accent-orange);
        box-shadow: 0 0 0 3px rgba(255, 140, 66, 0.2);
      }
      
      .input-icon {
        padding: 0 16px;
        color: rgba(255, 255, 255, 0.7);
        font-size: 18px;
      }
      
      :deep(.glass-input) {
        flex: 1;
        
        .el-input__wrapper {
          background: transparent;
          border: none;
          box-shadow: none;
          padding: 12px 16px 12px 0;
          
          .el-input__inner {
            background: transparent;
            border: none;
            color: var(--text-primary);
            font-size: 14px;
            font-weight: 500;
            
            &::placeholder {
              color: var(--text-muted);
            }
          }
        }
      }
    }
    
    // Captcha specific styles
    .captcha-item {
      .captcha-wrapper {
        display: flex;
        gap: 12px;
        align-items: center;
        
        .captcha-input {
          flex: 1;
        }
        
        .captcha-image {
          width: 140px;
          height: 52px;
          padding: 0;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.2);
          border-radius: 12px;
          backdrop-filter: blur(10px);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          
          &:hover {
            background: rgba(255, 255, 255, 0.15);
            border-color: rgba(255, 255, 255, 0.3);
            transform: scale(1.02);
          }
          
          .captcha-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 12px;
          }
          
          .refresh-hint {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            font-size: 10px;
            text-align: center;
            padding: 2px;
            opacity: 0;
            transition: opacity 0.3s;
          }
          
          &:hover .refresh-hint {
            opacity: 1;
          }
        }
      }
    }
    
    // Form options
    .form-options {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      
      .remember-checkbox {
        :deep(.el-checkbox__label) {
          color: var(--text-primary);
          font-size: 14px;
          font-weight: 500;
        }
        
        :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
          background-color: var(--accent-primary);
          border-color: var(--accent-primary);
        }
      }
      
      .forgot-link {
        color: var(--accent-primary);
        font-size: 14px;
        text-decoration: none;
        transition: all 0.3s;
        
        &:hover {
          color: var(--accent-amber);
          text-shadow: 0 0 8px rgba(255, 140, 66, 0.5);
        }
      }
    }
    
    // Submit button
    .submit-item {
      margin-bottom: 0;
      
      :deep(.glass-login-btn) {
        width: 100%;
        height: 48px;
        background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));
        border: none;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 600;
        color: white;
        box-shadow: 0 8px 25px rgba(196, 149, 108, 0.4);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 12px 35px rgba(196, 149, 108, 0.6);
        }
        
        &:active {
          transform: translateY(0);
        }
        
        .btn-icon {
          margin-right: 8px;
          font-size: 18px;
        }
        
        .loading-text {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          
          .loading-spinner {
            width: 16px;
            height: 16px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// Footer
.footer-info {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
  
  p {
    color: rgba(255, 255, 255, 0.7);
    font-size: 12px;
    margin: 0;
    text-align: center;
  }
}

// Responsive Design
@media (max-width: 768px) {
  .login-container {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 0 20px;
  }
  
  .welcome-section {
    padding: 24px;
    order: 2;
    
    .welcome-content {
      .logo-section {
        margin-bottom: 20px;
        
        .logo-icon {
          width: 60px;
          height: 60px;
          
          .logo-svg {
            font-size: 30px;
          }
        }
        
        .system-title {
          font-size: 20px;
        }
      }
      
      .feature-list {
        flex-direction: row;
        justify-content: center;
        flex-wrap: wrap;
        
        .feature-item {
          flex: 1;
          min-width: 120px;
          justify-content: center;
          padding: 8px 12px;
          
          span {
            font-size: 12px;
          }
        }
      }
    }
  }
  
  .form-section {
    order: 1;
  }
  
  .glass-login-form {
    padding: 24px;
    
    .form-header {
      margin-bottom: 24px;
      
      .form-title {
        font-size: 20px;
      }
    }
  }
  
  .ambient-bg .ambient-circle {
    &.ambient-circle-1 {
      width: 250px;
      height: 250px;
      top: -125px;
      right: -125px;
    }
    
    &.ambient-circle-2 {
      width: 200px;
      height: 200px;
      bottom: -100px;
      left: -100px;
    }
    
    &.ambient-circle-3, &.ambient-circle-4 {
      display: none;
    }
  }
}

@media (max-width: 480px) {
  .glass-login {
    padding: 10px;
  }
  
  .glass-login-form {
    padding: 20px;
    border-radius: 16px;
  }
  
  .captcha-item .captcha-wrapper {
    flex-direction: column;
    gap: 8px;
    
    .captcha-input {
      width: 100%;
    }
    
    .captcha-image {
      width: 100%;
      height: 40px;
    }
  }
}
</style>
